package com.framework.log.aspect;

import cn.hutool.json.JSONUtil;
import com.framework.log.enums.LogEnum;
import com.framework.log.ext.ISessionUtil;
import com.framework.log.model.SysLog;
import com.framework.log.service.ISysLogService;
import com.framework.log.utils.IpUtils;
import com.framework.log.utils.RequestUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;  
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * 系统日志切面类
 * 用于处理带有 @Log 注解的方法的日志记录
 *
 * @author zzg
 * @date 2024-12-27 13:55
 * @since 1.0
 */
@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private ISessionUtil sessionUtil;
    @Autowired
    private IpUtils ipUtils;
    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.framework.log.annotation.Log)")
    public void logPointcut() {
    }

    /**
     * 记录正常操作日志
     * 环绕通知，当被 @Log 注解标记的方法执行时触发
     *
     * @param joinPoint 切入点
     * @return 原方法的执行结果
     * @throws Throwable 可能抛出的异常
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        currentTime.set(System.currentTimeMillis());
        Object result = joinPoint.proceed();
        SysLog sysLog = setSysLog(joinPoint, LogEnum.LevelEnum.INFO);
        sysLogService.save(sysLog);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
    	SysLog sysLog = setSysLog(joinPoint, LogEnum.LevelEnum.ERROR);
        sysLog.setExceptionDetail(RequestUtil.getStackTrace(e));
        sysLogService.save(sysLog);
    }

    /**
     * 设置系统日志信息
     * 
     * @param joinPoint 切入点
     * @param levelEnum 日志级别
     * @return 封装的系统日志对象
     */
    private SysLog setSysLog(JoinPoint joinPoint, LogEnum.LevelEnum levelEnum) {
    	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.framework.log.annotation.Log aopLog = method.getAnnotation(com.framework.log.annotation.Log.class);
        String value = aopLog.value();

        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        
    	HttpServletRequest request = RequestUtil.getHttpServletRequest();

    	Long time = System.currentTimeMillis() - currentTime.get();
    	currentTime.remove();
    	
    	SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
    	sysLog.setLogLevel(levelEnum.name());
    	sysLog.setTime(time);
    	sysLog.setUserId(sessionUtil.getUserId());
    	sysLog.setUsername(sessionUtil.getUserName());
    	setRequestInfo(sysLog, request);
    	sysLog.setParams(getParameter(method, joinPoint.getArgs()));
    	sysLog.setMethod(methodName);
    	sysLog.setDescription(value);
    	return sysLog;
    }
    
    /**
     * 获取方法参数信息
     * 将方法的参数名和参数值转换成 JSON 字符串
     *
     * @param method 方法对象
     * @param args 方法参数值数组
     * @return 参数信息的 JSON 字符串
     */
    private String getParameter(Method method, Object[] args) {
        Parameter[] parameters = method.getParameters();
        
        Map<String, Object> paramMap = new HashMap<>(16);
        
        for (int i = 0; i < parameters.length; i++) {
        	paramMap.put(parameters[i].getName(), args[i]);
        }
        return JSONUtil.toJsonStr(paramMap);
    }

    private void setRequestInfo(SysLog sysLog, HttpServletRequest request) {
        String ip = ipUtils.getIp(request);
        sysLog.setRequestIp(ip);
        
        // 使用缓存优化 IP 地址解析
        if (StringUtils.isNotBlank(ip)) {
            try {
                sysLog.setAddress(ipUtils.getCityInfo(ip));
            } catch (Exception e) {
                log.warn("IP地址解析失败: {}", ip);
                sysLog.setAddress("未知");
            }
        }
    }
}
